import React, { Component } from 'react'
import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux'
import { pubReq } from '@/utils/request'
import styles from './page.module.css'
// import { siderMenuConfig } from './menu.config'
import {
  Layout,
  Breadcrumb,
  Button, Modal, Input, Tooltip
} from 'antd';
import {
  CheckCircleOutlined,
  HighlightOutlined,
} from '@ant-design/icons'
import { subRoutes } from '@/router'
import TopMenu from '@/components/menu/TopMenu'
import SiderMenu from '@/components/menu/SiderMenu'
import TopUser from '@/components/menu/TopUser'
import PubTag from '@/components/pub/PubTag'

const { Header, Content, Footer, Sider } = Layout;
const { confirm } = Modal
const mapStateToProps = (state) => {
  return {
    breadList: state.getIn(['bread', 'breadList']),
    isBread: state.getIn(['bread', 'isBread']),
    edit: {
      html: state.getIn(['blog', 'edit', 'html']),
      text: state.getIn(['blog', 'edit', 'text'])
    },
    tags: state.getIn(['blog', 'tags'])
  }
}
@withRouter
@connect(mapStateToProps)
class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      pathname: null,
      siderMenuData: {},
      // 上传还是草稿
      isBlur: '',
      // model
      blogModel: false,
      blogtooltip: false,
      blogLoading: false,
      tooltipText: ''
    }
  }

  componentDidMount() {
    const pathname = '/' + this.props.location.pathname.split('/')[1]
    const siderMenuData = subRoutes.filter(node => node.path === pathname)[0]
    this.setState({
      pathname,
      siderMenuData
    })
  }
  handleTopMenuChange = (item) => {
    let siderMenuData = subRoutes.filter(node => node.path === item.key)[0]
    this.setState({
      pathname: item.key,
      siderMenuData
    }, () => {
      this.props.history.push(item.key)
    })
  }
  handleSiderMenuChange = (item) => {
    this.props.history.push(item.key)
  }
  enterIconLoading = (blur) => {
    this.setState({ isBlur: blur })
    // console.log(this.props.edit)
    if (this.props.edit.html) {
      this.setState({ blogModel: true })
    } else {
      // 程序化的modal
      let secondsToGo = 5;
      const modal = Modal.warning({
        centered: true,
        title: '填写内容为空或未更改',
        content: `会在 ${secondsToGo} 秒之后回到编辑界面`,
      });
      const timer = setInterval(() => {
        secondsToGo -= 1;
        modal.update({
          content: `会在 ${secondsToGo} 秒之后回到编辑界面`,
        });
      }, 1000);
      setTimeout(() => {
        clearInterval(timer);
        modal.destroy();
      }, secondsToGo * 1000);
    }

  }
  handleOk = () => {
    this.setState({ blogLoading: true })//按钮// loading节流
    if (sessionStorage.getItem('bloger')) {//判断登录
      const title = this.modelInput.state.value
      const mydata = { ...this.props.edit, isPub: this.state.isBlur, isDraft: !this.state.isBlur, title, tags: this.props.tags }
      if (title && this.props.tags.length > 1) {//判断不为空
        let data = null
        if (this.props.location.state) {
          data = { ...mydata, id: this.props.location.state }
        } else {
          data = { ...mydata }
        }
        pubReq(data).then(res => {
          this.setState({ blogLoading: false, blogModel: false })
          // this.props.getTags(['请选择'])//组件被销毁,内部已恢复原始状态
          // this.modelInput.state.value = ''
          confirm({
            title: '上传或保存成功',
            icon: <CheckCircleOutlined style={{ color: '#1da57a' }} />,
            content: '是否马上去文章管理?',
            onOk: () => {
              this.props.history.push('/pub/articles')
            },
            onCancel() { }
          });
        })
      } else {
        this.setState({ blogtooltip: true, tooltipText: "标题或类别不能为空" }, () => {
          setTimeout(() => {
            this.setState({ blogtooltip: false, blogLoading: false, tooltipText: '' })
          }, 1000)
        })
      }
    } else {
      this.setState({ blogtooltip: true, tooltipText: "未登录无法发表" }, () => {
        setTimeout(() => {
          this.setState({ blogtooltip: false, blogLoading: false, tooltipText: '' })
        }, 1000)
      })
    }
  }
  render() {
    const { pathname, siderMenuData, blogtooltip, blogLoading, tooltipText } = this.state
    const {
      breadList,
      isBread } = this.props
    return (
      <Layout className={styles.layout}>
        {/* 头部 */}
        <Header className={styles.header} >
          <div className={styles.logobox}>
            {/* <Logo /> */}
                  t-blog
                </div>
          <div className={styles.topMenuItems}>
            <TopMenu
              path={pathname}
              handleTopMenuChange={this.handleTopMenuChange}
            />
          </div>
          <div>
            <TopUser />
          </div>
        </Header>
        {/* 中间部分 */}
        <Layout hasSider={true}>
          {/** trigger自定义触发器
           *  <Button type="primary" onClick={this.toggleCollapsed} style={{ marginBottom: 16 }}>
           *   {React.createElement(this.state.collapsed ? MenuUnfoldOutlined : MenuFoldOutlined)}
           *  </Button>
           */}
          {/* sider的触发器: collapsible={true}和collapsedWidth={0}会自动出现trigger */}
          <Sider
            theme="dark"
            // 配置 breakpoint 属性即生效，视窗宽度小于 breakpoint 时 Sider 缩小为 collapsedWidth 宽度
            // md: '768px', 小于ipad平板
            breakpoint="md"
            // 是否可收起
            collapsible={true}
            // 收缩宽度，设置为 0 会出现特殊 trigger
            collapsedWidth={0}
            defaultCollapsed={window.innerWidth < 768 ? true : false}
            className={styles.sider}
            width={150}
          >
            <SiderMenu siderMenuData={siderMenuData} handleSiderMenuChange={this.handleSiderMenuChange} />
          </Sider>

          <Content style={{ padding: '20px 20px 0 36px', overflowY: 'auto' }}>
            {/* 面包屑 */}
            {
              isBread ?
                <Breadcrumb separator=">" style={{ height: '10%' }}>
                  {
                    breadList.map(item => {
                      return <Breadcrumb.Item key={item}>{item}</Breadcrumb.Item>
                    })
                  }
                </Breadcrumb> : ''
            }
            {/* 插槽 */}
            <div style={{
              background: '#fff',
              padding: '24px 12px 12px 24px',
              borderRadius: '10px',
              minHeight: '90%'
            }}>
              {/* 插槽 */}
              {this.props.children}
            </div>
            {/* 按钮 */}
            {
              !isBread ?
                <div style={{ height: '10%', display: 'flex', alignItems: 'center' }}>
                  <Button
                    type="primary"
                    style={{ margin: '0 2px' }}
                    icon={<CheckCircleOutlined />}
                    // loading={this.state.iconLoading}
                    onClick={() => this.enterIconLoading(true)}
                  >发布文章</Button>
                  <Button
                    style={{ margin: '0 2px' }}
                    type="primary"
                    icon={<HighlightOutlined />}
                    // loading={this.state.iconLoading}
                    onClick={() => this.enterIconLoading(false)}
                  >存入草稿</Button>
                </div>
                : ''
            }
            <Modal
              title="设置标题和分类"
              // cancelText="取消"
              // okText="上传或保存"
              centered={true}
              visible={this.state.blogModel}
              // 关闭时销毁 Modal 里的子元素
              destroyOnClose={true}
              // onOk={this.handleOk}
              onCancel={() => this.setState({ blogModel: false })}
              footer={[
                // 数组
                <Button key="back" onClick={() => this.setState({ blogModel: false })}>
                  取消
                </Button>,
                <Tooltip key="submit-tip" placement="topLeft" title={tooltipText} arrowPointAtCenter visible={blogtooltip}>
                  {/* 设置了 arrowPointAtCenter 后，箭头将指向目标元素的中心。 */}
                  <Button key="submit" type="primary" loading={blogLoading} onClick={this.handleOk}>
                    上传或保存
                  </Button>
                </Tooltip>
              ]}
            >
              <div>
                <Input ref={(node) => this.modelInput = node} />
                {/* 分类 */}
                <PubTag />
              </div>
            </Modal>
          </Content>
        </Layout>

        {/* 底部 */}
        <Footer style={{ textAlign: 'center', padding: '10px 0' }}>
          <div>
            t-blog ©2020 topaz&nbsp;
            <a href="http://www.beian.miit.gov.cn/">鄂ICP备20003314号</a>
          </div>
        </Footer>
      </Layout >
    )
  }
}
export default App
